#!/usr/bin/env python3
#encoding=utf-8
import requests
from json import loads
from random import randint

class Bilibili:
    def __init__(self):
        self.url = "http://api.vc.bilibili.com/board/v1/ranking/top"
        self.Root_Path = "/Users/hades_x/Desktop/Python/Python_Spliders/video"
        self.header = {
            "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"
        }
        self.param = {
                "page_size" : "10",
                "next_offset" : str(randint(1,10)),
                "tag" : "今日热门",
                "platform" : "pc"
                
        }
        
    def run(self):
        html = requests.get(self.url,params = self.param,headers = self.header)
        bilibili_json = loads(html.text)
        num = 0
        for i in bilibili_json['data']['items']:
            self.download(i['item']['video_playurl'],str(num))
            num+=1
    
    def download(self,url,name):
        try:
            Path = self.Root_Path+"/"+name+".mp4"
            print(name)
            Content = requests.get(url,headers=self.header)
            with open(Path,"wb+") as f:
                f.write(Content.content)
            print("\033[1;32m[+]\033[0m Download"+Path+"Success")
        except:
            print("\033[1;31m[-]\033[0m Download"+Path+"Failed")

if __name__ == "__main__":
    A = Bilibili()
    A.run()
